#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define CNT         20
#define FILENAME    "/tmp/out1.txt"
#define BUFSIZE     32

int main(void)
{
    FILE *fp = NULL;
    int i;
    pid_t pid;
    char buf[BUFSIZE] = {0};

    fp = fopen(FILENAME, "w+");

    if (NULL == fp) {
        fprintf(stderr, "fopen() failed");
        return 1;
    }

    fputc('0', fp);
    fclose(fp);

    for (i = 0; i < CNT; i++) {
        pid = fork();

        if (-1 == pid) {
            perror("fork()");
            exit(1);
        }

        if (0 == pid) {
            fp = fopen(FILENAME, "r+");

            if (NULL == fp) {
                fprintf(stderr, "fopen() failed");
                return 1;
            }

            fgets(buf, BUFSIZE, fp);
            rewind(fp);
            fprintf(fp, "%d", atoi(buf) + 1);
            memset(buf, 0, BUFSIZE); // 清理缓冲区
            fclose(fp);

            return 0;
        }
    }

    for (i = 0; i < CNT; i++) 
        wait(NULL);

    fp = fopen(FILENAME, "a");

    if (NULL == fp) {
        fprintf(stderr, "fopen() failed");
        return 1;
    }

    fputc('\n', fp);
    fclose(fp);

    return 0;
}

